<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程星期" prop="courseWeek">
        <el-select v-model="queryParams.courseWeek" placeholder="请选择课程星期" clearable>
          <el-option
            v-for="dict in dict.type.course_week"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程节数" prop="courseSequence">
        <el-select v-model="queryParams.courseSequence" placeholder="请选择课程节数" clearable>
          <el-option
            v-for="dict in dict.type.course_sequence"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程学分" prop="courseCredit">
        <el-select v-model="queryParams.courseCredit" placeholder="请选择课程学分" clearable>
          <el-option
            v-for="dict in dict.type.course_credit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程学时" prop="courseHours">
        <el-select v-model="queryParams.courseHours" placeholder="请选择课程学时" clearable>
          <el-option
            v-for="dict in dict.type.course_hours"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程类型" prop="courseType">
        <el-select v-model="queryParams.courseType" placeholder="请选择课程类型" clearable>
          <el-option
            v-for="dict in dict.type.course_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="课程教室" prop="classroom">
        <el-input
          v-model="queryParams.classroom"
          placeholder="请输入课程教室"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程开始时间" prop="startDate">
        <el-date-picker clearable
                        v-model="queryParams.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择课程开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="课程结束时间" prop="endDate">
        <el-date-picker clearable
                        v-model="queryParams.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择课程结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入用户昵称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:selectCourse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:selectCourse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:selectCourse:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:selectCourse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="selectCourseList" @selection-change="handleSelectionChange">
      <!--<el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="课程ID" align="center" prop="courseId" />
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="课程描述" align="center" prop="courseDescription" />
      <el-table-column label="课程星期" align="center" prop="courseWeek">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_week" :value="scope.row.courseWeek"/>
        </template>
      </el-table-column>
      <el-table-column label="课程节数" align="center" prop="courseSequence">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_sequence" :value="scope.row.courseSequence"/>
        </template>
      </el-table-column>
      <el-table-column label="课程学分" align="center" prop="courseCredit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_credit" :value="scope.row.courseCredit"/>
        </template>
      </el-table-column>
      <el-table-column label="课程学时" align="center" prop="courseHours">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_hours" :value="scope.row.courseHours"/>
        </template>
      </el-table-column>
      <el-table-column label="课程类型" align="center" prop="courseType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.course_type" :value="scope.row.courseType"/>
        </template>
      </el-table-column>
      <el-table-column label="课程教室" align="center" prop="classroom" />
      <el-table-column label="课程开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程结束时间" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="部门名称" align="center" prop="deptName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:selectCourse:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:selectCourse:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            :type="scope.row.isSelected ? 'danger' : 'primary'"
            :icon="scope.row.isSelected ? 'el-icon-close' : 'el-icon-check'"
            @click="scope.row.isSelected ? handleCancel(scope.row) : handleConfirm(scope.row)"
            v-hasPermi="['course:selectCourse:confirm']"
          >
            {{ scope.row.isSelected ? '退课' : '选课' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改我的选课对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSelectCourse, getSelectCourse, delSelectCourse, addSelectCourse, updateSelectCourse, getCourseSelectionStatus, confirmSelection, cancelSelection } from "@/api/course/selectCourse";
import Vue from "vue";

export default {
  name: "SelectCourse",
  dicts: ['course_hours', 'course_type', 'course_sequence', 'course_credit', 'course_week'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 选课列表的表格数据
      selectCourseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        courseWeek: null,
        courseSequence: null,
        courseCredit: null,
        courseHours: null,
        courseType: null,
        classroom: null,
        startDate: null,
        endDate: null,
        nickName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseId: [
          { required: true, message: "课程ID不能为空", trigger: "blur" }
        ],
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
        courseDescription: [
          { required: true, message: "课程描述不能为空", trigger: "blur" }
        ],
        courseWeek: [
          { required: true, message: "课程星期不能为空", trigger: "change" }
        ],
        courseSequence: [
          { required: true, message: "课程节数不能为空", trigger: "change" }
        ],
        classroom: [
          { required: true, message: "课程教室不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询我的选课列表 */
    getList() {
      this.loading = true;
      listSelectCourse(this.queryParams).then(response => {
        this.selectCourseList = response.rows;
        this.total = response.total;
        // 为每个课程动态添加 isSelected 属性，并确保响应式
        this.selectCourseList.forEach(course => {
          Vue.set(course, 'isSelected', false);
        });
        // 为每个课程查询选课状态
        const promises = this.selectCourseList.map(course => {
          return getCourseSelectionStatus(course.courseId).then(res => {
            course.isSelected = res.data;
            return course;
          });
        });
        // 等待所有查询完成
        Promise.all(promises).then(() => {
          this.loading = false;
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: null,
        courseName: null,
        courseDescription: null,
        courseWeek: null,
        courseSequence: null,
        courseCredit: null,
        courseHours: null,
        courseType: null,
        classroom: null,
        startDate: null,
        endDate: null,
        nickName: null,
        deptName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加我的选课";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const courseId = row.courseId || this.ids
      getSelectCourse(courseId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改我的选课";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.courseId != null) {
            updateSelectCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSelectCourse(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids;
      this.$modal.confirm('是否确认删除我的选课编号为"' + courseIds + '"的数据项？').then(function() {
        return delSelectCourse(courseIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('course/selectCourse/export', {
        ...this.queryParams
      }, `selectCourse_${new Date().getTime()}.xlsx`)
    },
    /** 确认选课按钮操作 */
    handleConfirm(row) {
      // 过滤出已选中且与当前要选课程时间冲突的课程
      const conflictedCourses = this.selectCourseList.filter(
        (course) =>
          course.isSelected &&
          course.courseId!== row.courseId &&
          course.courseWeek === row.courseWeek &&
          course.courseSequence === row.courseSequence
      );

      // 如果存在冲突课程
      if (conflictedCourses.length > 0) {
        // 提取冲突课程的名称并拼接成字符串
        const conflictCourseNames = conflictedCourses.map(
          (course) => course.courseName
        ).join("、");
        // 弹出错误提示，告知用户不能选当前课程及冲突课程名称
        this.$modal.msgError(
          `不能选当前课程，与其他课程（${conflictCourseNames}）时间冲突`
        );
        // 直接返回，不执行后续的选课操作
        return;
      }
      // 如果不存在冲突，执行选课操作
      confirmSelection(row.courseId)
        .then(response => {
          this.$modal.msgSuccess("选课成功");
          this.getList();
        })
        .catch(error => {
          this.$modal.msgError("选课失败：" + error.message);
        });
    },
    /** 退选课程按钮操作 */
    handleCancel(row){
      const courseId = row.courseId;
      const courseName = row.courseName;
      this.$modal.confirm('是否确认退选课程编号为"' + courseId + '"，课程名称为"'+ courseName +'"的数据项？').then(function() {
        return cancelSelection(courseId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("退课成功");
      }).catch(() => {});
    }
  }
};
</script>
